/*
 * Created on 2004-9-18
 */
package org.nanhill.commons.servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.nanhill.commons.lang.StringKit;

/**
 * <code>
 *<filter>
 *	<filter-name>encoding</filter-name>
 *	<filter-class>org.nanhill.commons.servlet.filter.CharacterEncodingFilter</filter-class>
 *	<init-param>
 *		<param-name>forceEncoding</param-name>
 *		<param-value>true</param-value>
 *	</init-param>
 *	<init-param>
 *		<param-name>encoding</param-name>
 *		<param-value>UTF-8</param-value>
 *	</init-param>
 *</filter>
 *<filter-mapping>
 *		<filter-name>encoding</filter-name>
 *		<url-pattern>/*.do</url-pattern>
 *</filter-mapping>
 * </code>
 * 
 * @author alin [xalinx at gmail dot com]
 * @version 1.0
 */

public class CharacterEncodingFilter implements Filter {
	/**
	 * The default character encoding to set for requests that pass through this
	 * filter.
	 */
	protected String encoding = null;

	/**
	 * Should a character encoding specified by the client be ignored?
	 */
	protected boolean forceEncoding = false;

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (forceEncoding) {
			request.setCharacterEncoding(this.encoding);
		}
		// Pass control on to the next filter
		chain.doFilter(request, response);
	}

	/**
	 * Place this filter into service.
	 * 
	 * @param filterConfig
	 *            The filter configuration object
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.encoding = filterConfig.getInitParameter("encoding");
		String forceEncoding = filterConfig.getInitParameter("forceEncoding");
		if (forceEncoding != null) {
			if (this.encoding == null) {
				throw new ServletException(
						"Filter config error: must init encoding and forceEncoding parameters together.");
			}
			this.forceEncoding = StringKit
					.stringToBooleanTrueFirst(forceEncoding);
		}
	}

}
